import Vue from "vue";
import Router from "vue-router";
import Home from "./views/Home.vue";
import store from './util/store';
import * as types from './util/types'

Vue.use(Router);

const router = new Router({
    routes: [
        {
            path: "/",
            name: "home",
            component: Home,
            children:[
                {
                    path:'/users',
                    name:'用户管理',
                    component:()=>import(/* webpackChunkName: "users" */ "./views/Users.vue")
                }
            ]
        },
        {
            path: "/login",
            name: "login",
            meta: {
                permitAll: true,  // 添加该字段，表示进入这个路由是需要登录的
            },
            // route level code-splitting
            // this generates a separate chunk (about.[hash].js) for this route
            // which is lazy-loaded when the route is visited.
            component: () =>
                import(/* webpackChunkName: "login" */ "./views/Login.vue")
        },
        {
            path: "/about",
            name: "about",
            // route level code-splitting
            // this generates a separate chunk (about.[hash].js) for this route
            // which is lazy-loaded when the route is visited.
            component: () =>
                import(/* webpackChunkName: "about" */ "./views/About.vue")
        }
    ]
});

if (window.localStorage.getItem('token')) {
    store.commit(types.LOGIN, window.localStorage.getItem('token'))
}

router.beforeEach((to, from, next) => {
    if (!to.meta.permitAll) {  // 判断该路由是否需要登录权限
        if (store.state.token) {  // 通过vuex state获取当前的token是否存在
            next();
        }
        else {
            next({
                path: '/login',
                query: {redirect: to.fullPath}  // 将跳转的路由path作为参数，登录成功后跳转到该路由
            })
        }
    }
    else {
        next();
    }
});

export default router;